<?php

namespace App\Services\Address\Address;

use App\Models\Address\Address;
use Illuminate\Support\Facades\Redis;

/**
 * 地址逻辑层
 * Class AddressLogic
 * @package App\Services\Address\Address
 */
class AddressLogic
{

    //添加新地区
    public function createAddress($data)
    {
        $rst = Address::insert($data);

        if ($rst != 1) {
            return auto_failure (['status' => false],'添加新地区失败！');
        }
        return auto_return(['nums' => $rst],'添加新地区成功！');
    }

    // 编辑地区信息
    public function editAddress($data)
    {
        $rst =Address::where('id',$data['id'])
            ->update($data);
        if ($rst === false) {
            return auto_failure ($data,'地区信息更改失败！');
        } elseif ($rst === 0) {
            return auto_failure ($data,'地区信息未作改动！');
        }

        return auto_return(['number' => $rst],'地区信息更改成功！');
    }

    // 全部地区列表获取
    public function addressList()
    {
        $arr = Address::get()->toArray();
        $list = _make_tree($arr);
        return auto_return($list);
    }

    // 某一类地区列表获取
    public function someAddressList($data): array
    {
        $arr = Address::where($data)
            ->get()->toArray();
        return auto_return($arr);
    }

    /**
     * 获取城市数据列表（适配vant组件）
     * @return array
     */
    public function getAddrList()
    {
        $list = $this->getFromRedis();
        if (!$list) {
            $provinceData = Address::whereIn('pid', [0])->get()->toArray();

            $p = $this->format($provinceData, 'province_list');

            $provinceIds = array_column($provinceData, 'id');
            $cityData = Address::whereIn('pid', $provinceIds)->get()->toArray();

            $c = $this->format($cityData, 'city_list');

            $cityIds = array_column($cityData, 'id');
            $countyData = Address::whereIn('pid', $cityIds)->get()->toArray();

            $cou = $this->format($countyData, 'county_list');

            $list = array_merge($p, $c, $cou);
            $this->saveToRedis($list);
        } else {
            $list = json_decode($list);
        }
        return auto_return($list);
    }

    private function format($data, $key)
    {
        foreach ($data as $v) {
            $list[$key][$v['id']] = $v['name'];
        }
        return $list;
    }

    private function saveToRedis($arr)
    {
        $str = json_encode($arr, true);
        $res = Redis::set(ADDRESS_LIST, $str);
        return $res;
    }

    private function getFromRedis()
    {
        $res = Redis::get(ADDRESS_LIST);
        return $res;
    }
}
